package com.istock.monitor.agent.spring;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.util.ClassUtils;

public class MonitorAspectJExpressionPointCut extends AspectJExpressionPointcut {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public boolean matches(Class<?> targetClass) {
		if(!canProxy(targetClass)) {
			return false;
		}
		return super.matches(targetClass);
	}

	@Override
	public boolean matches(Method method, Class<?> targetClass, boolean beanHasIntroductions) {
		if(!canProxy(targetClass)) {
			return false;
		}
		return super.matches(method, targetClass, beanHasIntroductions);
	}

	@Override
	public boolean matches(Method method, Class<?> targetClass) {
		if(!canProxy(targetClass)) {
			return false;
		}
		return super.matches(method, targetClass);
	}

	@Override
	public boolean matches(Method method, Class<?> targetClass, Object[] args) {
		if(!canProxy(targetClass)) {
			return false;
		}
		return super.matches(method, targetClass, args);
	}

	private boolean canProxy(Class targetClass) {
		
		boolean result = !targetClass.isEnum() && !Modifier.isFinal(targetClass.getModifiers()) && ConstructorUtils.getMatchingAccessibleConstructor(targetClass, null) != null
				&& !targetClass.getCanonicalName().equalsIgnoreCase("com.istock.monitor.agent.spring.DataSourceBeanPostProcessor")
				&& ClassUtils.getStaticMethod(targetClass, "getInstance", null) == null
				&& !targetClass.getCanonicalName().startsWith("net.sf.ehcache")
				&& !targetClass.getCanonicalName().startsWith("org.apache.ibatis")
				&& !targetClass.getCanonicalName().equalsIgnoreCase("org.springframework.transaction.annotation.AnnotationTransactionAttributeSource")
				&& !ClassUtils.isAssignable(targetClass,org.springframework.beans.factory.FactoryBean.class);
		System.out.println(targetClass + "================" + result);
		return result;
	}
}
